//
//  XHDrawAdViewController.m
//  XHAdSDKTest
//
//  Created by 昱胜 on 2022/7/21.
//

#import "XHDrawAdViewController.h"
//广告头文件
#import <XHAdSDK/XHAdSDK.h>

@interface XHDrawAdViewController ()<UITableViewDataSource, UITableViewDelegate,XHDrawAdDataDelegate>
@property (strong, nonatomic) UITableView *tableView;
@property (nonatomic, copy) NSArray *dataSource;
@property (nonatomic, strong) BUNativeExpressAdManager *nativeExpressAdManager;
@property (strong, nonatomic) NSTimer *timer;

@end

@implementation XHDrawAdViewController

- (void)dealloc {
    _tableView.delegate = nil;
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.pagingEnabled = YES;
#if defined(__IPHONE_11_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_11_0
    if ([self.tableView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
        if (@available(iOS 11.0, *)) {
            self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            self.tableView.estimatedRowHeight = 0;
        }
    }
#else
    self.automaticallyAdjustsScrollViewInsets = NO;
#endif
    [self.view addSubview:self.tableView];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"BUDNativeExpressCell"];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
//    [self.tableView registerClass:[BUDDrawAdTableViewCell class] forCellReuseIdentifier:@"BUDDrawAdTableViewCell"];
//    [self.tableView registerClass:[BUDDrawBaseTableViewCell class] forCellReuseIdentifier:@"BUDDrawBaseTableViewCell"];
    
    NSMutableArray *datas = [NSMutableArray array];
    for (NSInteger i =0 ; i <= 15; i++) {
        [datas addObject:@"App tableViewcell"];
    }
    self.dataSource = [datas copy];
    
    [self.tableView reloadData];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(13, 34, 30, 30);
    [btn setImage:[UIImage imageNamed:@"draw_back.png"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(closeVC) forControlEvents:UIControlEventTouchUpInside];
    [self.view bringSubviewToFront:btn];
    [self.view addSubview:btn];
    btn.accessibilityIdentifier = @"draw_back";
    // Do any additional setup after loading the view.
    [self loadData];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.timer invalidate];
    self.timer = nil;
}

- (void)loadData {
    XHAdCenter * center = [XHAdCenter new];
    XHDrawAdData * data = [XHDrawAdData new];
    data.adCount = 3;
    data.rootViewController = self;
    data.drawAdDelegate = self;
    __weak typeof(self) weakSelf = self;
    [center xh_showDrawAd:data appId:@"289150002507284541" adType:XHAdType_CSJ complate:^(NSArray<__kindof BUNativeExpressAdView *> * _Nonnull adViewAry) {
        if (adViewAry.count) {
            NSMutableArray *dataSources = [weakSelf.dataSource mutableCopy];
            [adViewAry enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                BUNativeExpressAdView *expressView = (BUNativeExpressAdView *)obj;
                expressView.rootViewController = weakSelf;
                // important: 此处会进行WKWebview的渲染，建议一次最多预加载三个广告，如果超过3个会很大概率导致WKWebview渲染失败。
                [expressView render];
                NSUInteger index = arc4random() % (weakSelf.dataSource.count-3)+2;
                [dataSources insertObject:expressView atIndex:index];
            }];
            weakSelf.dataSource = [dataSources copy];
        }
        [weakSelf.tableView reloadData];
    }];
}

- (void)closeVC{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

#pragma mark - XHDrawAdDataDelegate
/** 广告加载失败，msg加载失败说明（如果重新请求广告，注意：只重新请求一次）*/
- (void)xh_onDrawActionAdFail:(NSString *)errorString {
    
}

/** 广告渲染成功 */
- (void)xh_onDrawActionAdExposure {
    
}

/** 广告被关闭 */
- (void)xh_onDrawActionAdDismiss {
    
}

/** 广告被点击 */
- (void)xh_onDrawActionAdClicked {
    
}

#pragma mark --- tableView dataSource&delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger index = indexPath.row;
    id model = self.dataSource[index];
    if ([model isKindOfClass:[BUNativeExpressAdView class]]) {
        UITableViewCell *cell = nil;
        cell = [self.tableView dequeueReusableCellWithIdentifier:@"BUDNativeExpressCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [self addAccessibilityIdentifier:model];
        // 重用BUNativeExpressAdView，先把之前的广告试图取下来，再添加上当前视图
        UIView *subView = (UIView *)[cell.contentView viewWithTag:1000];
        if ([subView superview]) {
            [subView removeFromSuperview];
        }
        
        UIView *view = model;
        view.tag = 1000;
        [cell.contentView addSubview:view];
        return cell;
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        cell.textLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row];
        cell.imageView.backgroundColor = [UIColor orangeColor];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger index = indexPath.row;
    id model = self.dataSource[index];
    if ([model isKindOfClass:[BUNativeExpressAdView class]]) {
        [self removeAccessibilityIdentifier:(BUNativeExpressAdView *)model];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [UIScreen mainScreen].bounds.size.height;
}

#pragma mark - AccessibilityIdentifier
- (void)addAccessibilityIdentifier:(BUNativeExpressAdView *)adView {
    adView.accessibilityIdentifier = @"express_draw_view";
}

- (void)removeAccessibilityIdentifier:(BUNativeExpressAdView *)adView {
    adView.accessibilityIdentifier = nil;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
